package com.xlisteven.web5.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.xlisteven.web5.pojo.User;
import com.xlisteven.web5.service.UserService;


@Controller
@SuppressWarnings("all")
public class UserController {

	@Autowired
	UserService userService;

	@RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
	private String fildUpload(User user,
			@RequestParam(value = "uploadfile1", required = false) MultipartFile uploadfile1,
			HttpServletRequest request) throws Exception {
		// 基本表单
		System.out.println(user.toString());

		// 获得物理路径webapp所在路径
		String pathRoot = request.getSession().getServletContext().getRealPath("");
		String projectPath = request.getContextPath();
		String path = "";
		if (!uploadfile1.isEmpty()) {
			// 生成uuid作为文件名称
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			// 获得文件类型（可以判断如果不是图片，禁止上传）
			String contentType = uploadfile1.getContentType();
			// 获得文件后缀名称
			String imageName = contentType.substring(contentType.indexOf("/") + 1);
			path = "/upload/" + uuid + "." + imageName;
			uploadfile1.transferTo(new File(pathRoot + path));
		}
		String dbPath =projectPath+path;
		user.setImgPath(dbPath);
		userService.insertUser(user);
		return "redirect:/findAllUser";
	}

	@RequestMapping("/findAllUser")
	public String findAllUser(Model model) {
		List<User> userList = userService.findAllUser();
		model.addAttribute("userList", userList);
		return "userList";
	}
}
